import traceback
from typing import List

from mg_app_framework import get_logger

from common_bind_service.context_utils.context_utils import ContextUtils
from common_bind_service.models.dict_model.mq.device_config_entity import DeviceConfigEntity


async def process_WebLayout_produce_unit_import_application_used(data: List[DeviceConfigEntity]):
    data.sort(key=lambda x: (x["车间代号"], x["生产单元代号"], x["工段顺序"], x["设备顺序"]))
    device_code_info_dict = {}
    dev_code_table_number_map = {}
    for item in data:
        device_code_info_dict[item["设备编码"]] = item
        dev_code_table_number_map[item["设备编码"]] = str(item.get('机台号', ''))

    ContextUtils.set_device_code_info_dict(device_code_info_dict)
    ContextUtils.set_dev_code_table_number_map(dev_code_table_number_map)


# 常见的通用key,
rabbitmq_message_key_to_handler = {
    # 其他消息列表参考: http://192.168.250.237:10083/issues/1321?next_issue_id=1320
    'WebLayout_produce_unit_import_application_used': process_WebLayout_produce_unit_import_application_used,
    # 生产单元基础配置
}


async def msg_dispatch(message):
    key = message["key"]
    data = message["data"]
    try:
        await rabbitmq_message_key_to_handler[key](data)
    except KeyError:
        get_logger().warning(f'key [ {key} ] process func not exists.')
    except Exception:
        get_logger().error(f'process msg: [ {key} ] error.\n data: {data}.\n {traceback.format_exc()}')
